package com.corgi.encrypt.advice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.corgi.encrypt.RSAUtil;
import com.corgi.encrypt.util.Base64Util;
import com.corgi.encrypt.util.RsaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.stream.Collectors;

/**
 * @title: DecryptHttpInputMessage
 * @description:
 * @author: dengmiao
 * @create: 2019-10-23 15:28
 **/
@Slf4j
public class DecryptHttpInputMessage implements HttpInputMessage {

    private HttpHeaders headers;

    private InputStream body;

    public DecryptHttpInputMessage(HttpInputMessage inputMessage, String privateKey, String charset, boolean showLog) throws Exception {
        if (StringUtils.isEmpty(privateKey)) {
            throw new IllegalArgumentException("privateKey is null");
        }

        this.headers = inputMessage.getHeaders();
        String content = new BufferedReader(new InputStreamReader(inputMessage.getBody()))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        String decryptBody;
        // log.debug("content: {}, isValid: {}, isValidObject: {}, isValidArray: {}", content, JSON.isValid(content), JSON.isValidObject(content), JSON.isValidArray(content));
        if (JSON.isValid(content)) {
            log.info("Unencrypted without decryption:{}", content);
            JSONObject jsonObject = JSON.parseObject(content);
            decryptBody = jsonObject.containsKey("encrypt") ?
                    RSAUtil.privateDecrypt(jsonObject.getString("encrypt"), privateKey) :
                    content;
        } else {
            StringBuilder json = new StringBuilder();
            content = content.replaceAll(" ", "+");

            if (!StringUtils.isEmpty(content)) {
                String[] contents = content.split("\\|");
                for (String value : contents) {
                    value = RSAUtil.privateDecrypt(value, privateKey);
                    // value = new String(RsaUtil.decrypt(Base64Util.decode(value), privateKey), charset);
                    json.append(value);
                }
            }
            decryptBody = json.toString();
            if(showLog) {
                log.info("Encrypted data received：{},After decryption：{}", content, decryptBody);
            }
        }
        this.body = new ByteArrayInputStream(decryptBody.getBytes());
    }

    @Override
    public InputStream getBody() throws IOException {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}
